package com.wj.algorithm.lintcode.string;

public class P78 {

    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length < 1) {
            return "";
        }
        if(strs.length == 1) {
            return strs[0];
        }
        int minLen = Integer.MAX_VALUE;
        for(String s : strs) {
            int l = s.length();
            if(l < minLen) {
                minLen = l;
            }
        }
        int sl = strs.length;
        StringBuilder b = new StringBuilder();
        for(int i = 0; i < minLen; i ++) {
            Character temp = null;
            for(int j = 0; j < sl; j ++) {
                if(temp == null) {
                    temp = strs[j].charAt(i);
                } else if(strs[j].charAt(i) != temp) {
                    temp = null;
                    break;
                }
            }
            if(temp != null) {
                b.append(temp);
            }
        }
        
        return b.toString();
    }
    
    public static void main(String[] args) {
        String[] arr = new String[]{
                "ABCDEFG", "ABCEFG", "ABCEFA"
        };
        
        System.out.println(new P78().longestCommonPrefix(arr));
    }
}
